package org.lagou.config;

import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * @author junbao
 */
@HandlesTypes({MyWebApplicationInitializer.class})
public class MySpringServletContainerInitializer implements ServletContainerInitializer {

    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {

        List<WebApplicationInitializer> initializers = new LinkedList();
        Iterator iterator;
        if(set != null) {
            iterator = set.iterator();
            while (iterator.hasNext()) {
                Class<?> next =  (Class)iterator.next();
                try {
                    initializers.add((WebApplicationInitializer) ReflectionUtils.accessibleConstructor(next, new Class[0]).newInstance());
                } catch (Throwable e) {
                    throw new ServletException("Failed to instantiate WebApplicationInitializer class", e);
                }
            }
        }
        if(initializers.isEmpty()){
            servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
        }else{
            servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
            AnnotationAwareOrderComparator.sort(initializers);
            iterator = initializers.iterator();
            while (iterator.hasNext()) {
                Object next =  iterator.next();
                WebApplicationInitializer initializer = new MyWebApplicationInitializer();
                initializer.onStartup(servletContext);
            }
        }
    }

}
